import { createSlice } from '@reduxjs/toolkit'
import loginJSON from '@/mock/login.json'
import userJSON from '@/mock/user.json'
import { clearToken, getToken, setToken } from '@/utils/axios/token'

const userStore = createSlice({
	name: 'user',
	// 数据状态
	initialState: {
		token: getToken() || '',
		userInfo: {}
	},
	// 同步修改方法
	reducers: {
		setUserToken(state: any, action) {
			state.token = action.payload
			setToken(state.token)
		},
		setUserInfo (state, action) {
      state.userInfo = action.payload
    },
		clearUserInfo (state) {
      state.token = ''
      state.userInfo = {}
      clearToken()
    }
	},
})

// 解构出actionCreater
const { setUserToken, setUserInfo, clearUserInfo } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

// 异步方法封装
const fetchLogin = (loginForm: any) => {
	return async (dispatch: any) => {
		// const res = await http.post('/login', loginForm)
		const res = loginJSON
		dispatch(setUserToken(res.token))
	}
}

const fetchUserInfo = () => {
  return async (dispatch: any) => {
    // const res = await http.get('/user/profile')
		const res = userJSON
    dispatch(setUserInfo(res.data))
  }
}

export { fetchLogin, fetchUserInfo, clearUserInfo }

export default userReducer
